//Copyright (c) 2006-2007 Microsoft Corporation.  All rights reserved
using System;
using System.Globalization;
using System.Xml;

using InvocationFramework.Common.Instrumentation;
using InvocationFramework.Common.Resources;

using InvocationFramework.Adapters.Pipeline;

namespace InvocationFramework.Adapters.Pipeline.Mock
{
    /// <summary>
    /// Filtro para generar ejecuciones simulada para pruebas unitarias
    /// </summary>
    /// <author>Rodolfo Finochietti 23/05/2006 23.53</author>
    public class MockFilter : IFilter
    {
        #region Private Vars

        private string _cacheFile;

        private bool _mockMode;

        #endregion

        #region IFilter Members

        /// <summary>
        /// Inicializa el filtro
        /// </summary>
        /// <param name="configuration">Configuracion del filtro</param>
        public void Init( XmlNode configuration )
        {
            try
            {
                //Configuro el filtro
                if ( configuration != null )
                {
                    _cacheFile = configuration.Attributes[ "cacheFile" ].Value;
                    _mockMode = Convert.ToBoolean( configuration.Attributes[ "mockMode" ].Value, CultureInfo.InvariantCulture );

                    //Configuro las propiedad en el cache
                    ResultCache.Instance.CacheFile = _cacheFile;
                    ResultCache.Instance.MockMode = _mockMode;

                    //Cargo el cache
                    ResultCache.Instance.Load( );
                }
            }
            catch ( Exception ex )
            {
                TraceHelper.Error( ex, Texts.MockFilterInitError );
                throw;
            }
        }

        /// <summary>
        /// Permite implementar la logica de ejecucion del filtro
        /// </summary>
        /// <param name="state">Estado del pipeline</param>
        /// <returns>Resultado de la ejecucion del filtro</returns>
        public FilterResult Process( PipelineState state )
        {
            if ( state != null )
            {
                if ( state.Pipeline == PipelineType.Input )
                {
                    ResultCacheEntry entry = ResultCache.Instance[ state.ExecutionInformation ];
                    if ( entry != null )
                        state.ExecutionInformation.Result = entry.Result;
                }
                else if ( state.Pipeline == PipelineType.Output )
                {
                    ResultCache.Instance.Add( state.ExecutionInformation );
                }
            }
            
            return FilterResult.Continue;
        }

        #endregion
    }
}